package lion.dev.text.charset;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * charset detector for byte arrays,inputstream and File,it use jchardet
 * first,and it return UTF-8 as default in case of detect failure
 *
 * <pre>
 * time   2013年10月14日
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class CharsetDetector {

	private static ICharsetDetect detector;
	private static final String DEFAULT_CHARSET = "UTF-8";

	public static String detect(byte[] src) {

		try {
			return getDetect().detect(src);
		} catch (IOException e) {
			return DEFAULT_CHARSET;
		}
	}

	public static String detect(InputStream src) {

		try {
			return getDetect().detect(src);
		} catch (IOException e) {
			return DEFAULT_CHARSET;
		}
	}

	public static String detect(File src) {

		try {
			return getDetect().detect(src);
		} catch (IOException e) {
			return DEFAULT_CHARSET;
		}
	}

	private static ICharsetDetect getDetect() {

		if (detector == null) {
			init();
		}
		return detector;
	}

	private static void init() {

		Class<? extends ICharsetDetect> clazz;
		try {
			Class.forName("info.monitorenter.cpdetector.io.JChardetFacade");
			clazz = MozillaCharsetDetector.class;
		} catch (Throwable e) {
			clazz = UTF8Detector.class;
		}
		try {
			detector = clazz.newInstance();
		} catch (Exception e) {

		}
	}
}
